﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Messaging.Nms.Core;
using Apache.NMS;
using System.Windows.Controls.Primitives;
using System.Windows;
using System.Windows.Controls;
using Apache.NMS.ActiveMQ;
using Apache.NMS.ActiveMQ.Commands;

namespace ModeloGaleriaNET
{
    public delegate void MessageReceivedDelegate(ActiveMQMessage message);
    public class ActiveMQSubscriber : IDisposable
    {
        private readonly string topicName = null;
        private readonly IConnectionFactory connectionFactory;
        private readonly IConnection connection;
        private readonly ISession session;
        private readonly IMessageConsumer consumer;
        private bool isDisposed = false;
        public event MessageReceivedDelegate OnMessageReceived;
        private string consumerId;

        public ActiveMQSubscriber(string topicName, string brokerUri, string clientId, string consumerId)
        {
            this.topicName = topicName;
            this.connectionFactory = new ConnectionFactory(brokerUri);
            this.connection = this.connectionFactory.CreateConnection();
            this.connection.RequestTimeout = TimeSpan.FromSeconds(ModeloGaleriaNET.Properties.Settings.Default.TimeOut);
            this.connection.ClientId = clientId;
            this.connection.Start();
            this.session = connection.CreateSession();
            ActiveMQTopic topic = new ActiveMQTopic(topicName);
            this.consumer = this.session.CreateDurableConsumer(topic, consumerId, "2 > 1", false);
            this.consumer.Listener += new MessageListener(OnMessage);
            this.consumerId = consumerId;
        }

        #region Members
        private delegate void SetTextIntoPanel();

        public void OnMessage(IMessage input)
        {
            ActiveMQMessage message = input as ActiveMQMessage;
            if (this.OnMessageReceived != null)
            {
                this.OnMessageReceived(message);
            }
        }

        public void Dispose()
        {
            if (!this.isDisposed)
            {
                this.consumer.Dispose();
                this.session.Dispose();
                this.connection.Dispose();
                this.isDisposed = true;
            }
        }
        #endregion
    }
}
